package com.example.demo.controller;

import com.example.demo.dto.TaskApprovalStatusDTO;
import com.example.demo.dto.TaskApprovalWithRawDataDTO;
import com.example.demo.dto.TaskApprovalNodeDetailDTO;
import com.example.demo.dto.UserTaskStatisticsDTO;
import com.example.demo.dto.DataSourceUserStatisticsDTO;
import com.example.demo.dto.DataSourceTaskStatisticsDTO;
import com.example.demo.request.ApproveTaskRequest;
import com.example.demo.request.CreateTaskApprovalStatusRequest;
import com.example.demo.request.ForwardTaskRequest;
import com.example.demo.response.ApiResponse;
import com.example.demo.dto.PageExtra;
import com.example.demo.service.TaskApprovalStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/task-approval-status")
public class TaskApprovalStatusController {

        @Autowired
        private TaskApprovalStatusService taskApprovalStatusService;


        @GetMapping
        public ResponseEntity<ApiResponse<List<TaskApprovalStatusDTO>>> getTaskApprovalStatuses(
                         @RequestParam(defaultValue = "0") int page,
                        @RequestParam(defaultValue = "10") int size,
                         @RequestParam(required = false) Long taskId,
                         @RequestParam(required = false) Long flowId,
                        HttpServletRequest request) {
                List<TaskApprovalStatusDTO> taskApprovalStatuses = taskApprovalStatusService
                                .getTaskApprovalStatuses(page, size, taskId, flowId);
                long total = taskApprovalStatusService.countTaskApprovalStatuses(taskId, flowId);
                PageExtra pageExtra = new PageExtra(page, size, total);

                return ResponseEntity.ok(
                                ApiResponse.success(taskApprovalStatuses, "查询成功", request.getRequestURI(), pageExtra));
        }


        @GetMapping("/{id}")
        public ResponseEntity<ApiResponse<TaskApprovalStatusDTO>> getTaskApprovalStatusById(
                        @PathVariable Long id,
                        HttpServletRequest request) {
                TaskApprovalStatusDTO taskApprovalStatusDTO = taskApprovalStatusService.getTaskApprovalStatusById(id);
                return ResponseEntity.ok(
                                ApiResponse.success(taskApprovalStatusDTO, "查询成功", request.getRequestURI(), null));
        }


        @PostMapping
        public ResponseEntity<ApiResponse<TaskApprovalStatusDTO>> createTaskApprovalStatus(
                        @Valid @RequestBody CreateTaskApprovalStatusRequest request,
                        HttpServletRequest httpRequest) {
                TaskApprovalStatusDTO taskApprovalStatusDTO = taskApprovalStatusService
                                .createTaskApprovalStatus(request);
                return ResponseEntity.ok(
                                ApiResponse.success(taskApprovalStatusDTO, "创建成功", httpRequest.getRequestURI(), null));
        }


        @PutMapping("/{id}")
        public ResponseEntity<ApiResponse<TaskApprovalStatusDTO>> updateTaskApprovalStatus(
                         @PathVariable Long id,
                        @Valid @RequestBody CreateTaskApprovalStatusRequest request,
                        HttpServletRequest httpRequest) {
                TaskApprovalStatusDTO taskApprovalStatusDTO = taskApprovalStatusService.updateTaskApprovalStatus(id,
                                request);
                return ResponseEntity.ok(
                                ApiResponse.success(taskApprovalStatusDTO, "更新成功", httpRequest.getRequestURI(), null));
        }


        @DeleteMapping("/{id}")
        public ResponseEntity<ApiResponse<Void>> deleteTaskApprovalStatus(
                         @PathVariable Long id,
                        HttpServletRequest request) {
                taskApprovalStatusService.deleteTaskApprovalStatus(id);
                return ResponseEntity.ok(
                                ApiResponse.success(null, "删除成功", request.getRequestURI(), null));
        }

//        @Operation(summary = "根据数据源ID初始化任务审批状态", description = "获取该数据源下未分发的任务，分发到流程，并为每个流程节点创建审批状态记录")
        @PostMapping("/initialize-by-datasource/{dataSourceId}")
        public ResponseEntity<ApiResponse<Integer>> initializeTaskApprovalStatusByDataSource(
                         @PathVariable Long dataSourceId,
                        HttpServletRequest request) {
                int createdCount = taskApprovalStatusService.initializeTaskApprovalStatusByDataSource(dataSourceId);
                return ResponseEntity.ok(
                                ApiResponse.success(createdCount,
                                                "初始化成功，共创建" + createdCount + "条审批状态记录",
                                                request.getRequestURI(), null));
        }


        @GetMapping("/task/{taskId}")
        public ResponseEntity<ApiResponse<List<TaskApprovalStatusDTO>>> getTaskApprovalStatusesByTaskId(
                        @PathVariable Long taskId,
                        HttpServletRequest request) {
                List<TaskApprovalStatusDTO> taskApprovalStatusDTOs = taskApprovalStatusService
                                .getTaskApprovalStatusesByTaskId(taskId);
                return ResponseEntity.ok(
                                ApiResponse.success(taskApprovalStatusDTOs, "查询成功", request.getRequestURI(), null));
        }


        @GetMapping("/flow/{flowId}")
        public ResponseEntity<ApiResponse<List<TaskApprovalStatusDTO>>> getTaskApprovalStatusesByFlowId(
                         @PathVariable Long flowId,
                        HttpServletRequest request) {
                List<TaskApprovalStatusDTO> taskApprovalStatusDTOs = taskApprovalStatusService
                                .getTaskApprovalStatusesByFlowId(flowId);
                return ResponseEntity.ok(
                                ApiResponse.success(taskApprovalStatusDTOs, "查询成功", request.getRequestURI(), null));
        }

//        @Operation(summary = "根据审批人ID获取处理中状态的审批列表", description = "根据审批人ID筛选状态为处理中(1)的审批状态列表")
        @GetMapping("/approver/{approverId}/processing")
        public ResponseEntity<ApiResponse<List<TaskApprovalStatusDTO>>> getTaskApprovalStatusesByApproverIdAndStatusProcessing(
                        @PathVariable Long approverId,
                        HttpServletRequest request) {
                List<TaskApprovalStatusDTO> taskApprovalStatusDTOs = taskApprovalStatusService
                                .getTaskApprovalStatusesByApproverIdAndStatusProcessing(approverId);
                return ResponseEntity.ok(
                                ApiResponse.success(taskApprovalStatusDTOs, "查询成功", request.getRequestURI(), null));
        }

//        @Operation(summary = "根据审批人ID获取已审批状态的审批列表", description = "根据审批人ID筛选状态为已审批(2)的审批状态列表")
        @GetMapping("/approver/{approverId}/approved")
        public ResponseEntity<ApiResponse<List<TaskApprovalStatusDTO>>> getTaskApprovalStatusesByApproverIdAndStatusApproved(
                         @PathVariable Long approverId,
                        HttpServletRequest request) {
                List<TaskApprovalStatusDTO> taskApprovalStatusDTOs = taskApprovalStatusService
                                .getTaskApprovalStatusesByApproverIdAndStatusApproved(approverId);
                return ResponseEntity.ok(
                                ApiResponse.success(taskApprovalStatusDTOs, "查询成功", request.getRequestURI(), null));
        }

//        @Operation(summary = "根据审批人ID获取处理中状态的审批列表(包含原始数据)", description = "根据审批人ID筛选状态为处理中(1)的审批状态列表，并包含原始数据")
        @GetMapping("/approver/{approverId}/processing-with-rawdata")
        public ResponseEntity<ApiResponse<List<TaskApprovalWithRawDataDTO>>> getTaskApprovalStatusesByApproverIdAndStatusProcessingWithRawData(
                         @PathVariable Long approverId,
                        HttpServletRequest request) {
                List<TaskApprovalWithRawDataDTO> taskApprovalStatusDTOs = taskApprovalStatusService
                                .getTaskApprovalStatusesByApproverIdAndStatusProcessingWithRawData(approverId);
                return ResponseEntity.ok(
                                ApiResponse.success(taskApprovalStatusDTOs, "查询成功", request.getRequestURI(), null));
        }


        @GetMapping("/task/{taskId}/node-details")
        public ResponseEntity<ApiResponse<List<TaskApprovalNodeDetailDTO>>> getTaskApprovalNodeDetailsByTaskId(
                         @PathVariable Long taskId,
                        HttpServletRequest request) {
                List<TaskApprovalNodeDetailDTO> nodeDetails = taskApprovalStatusService
                                .getTaskApprovalNodeDetailsByTaskId(taskId);
                return ResponseEntity.ok(
                                ApiResponse.success(nodeDetails, "查询成功", request.getRequestURI(), null));
        }

//        @Operation(summary = "根据任务ID获取当前正在执行审批的节点信息", description = "返回状态为处理中(1)的审批节点，供管理员执行审批操作")
        @GetMapping("/task/{taskId}/current-processing-node")
        public ResponseEntity<ApiResponse<TaskApprovalWithRawDataDTO>> getCurrentProcessingNodeByTaskId(
                         @PathVariable Long taskId,
                        HttpServletRequest request) {
                TaskApprovalWithRawDataDTO currentProcessingNode = taskApprovalStatusService
                                .getCurrentProcessingNodeByTaskId(taskId);
                return ResponseEntity.ok(
                                ApiResponse.success(currentProcessingNode, "查询成功", request.getRequestURI(), null));
        }

//        @Operation(summary = "审批任务", description = "根据传入的状态处理审批任务：已通过(2)则进入下一个节点；已拒绝(3)则返回上一个节点；已跳过(4)则跳过当前节点进入下一个节点")
    @PostMapping("/approve")
    public ResponseEntity<ApiResponse<TaskApprovalStatusDTO>> approveTask(
            @Valid @RequestBody ApproveTaskRequest request,
            HttpServletRequest httpRequest) {
        TaskApprovalStatusDTO taskApprovalStatusDTO = taskApprovalStatusService.approveTask(request);
        return ResponseEntity.ok(
                ApiResponse.success(taskApprovalStatusDTO, "审批成功", httpRequest.getRequestURI(), null));
    }
    
//    @Operation(summary = "转发任务", description = "将当前记录状态更新为5（已转发），并创建一条新记录给新审批人，状态设为1（处理中）")
    @PostMapping("/forward")
    public ResponseEntity<ApiResponse<TaskApprovalStatusDTO>> forwardTask(
            @Valid @RequestBody ForwardTaskRequest request,
            HttpServletRequest httpRequest) {
        TaskApprovalStatusDTO taskApprovalStatusDTO = taskApprovalStatusService.forwardTask(request);
        return ResponseEntity.ok(
                ApiResponse.success(taskApprovalStatusDTO, "转发成功", httpRequest.getRequestURI(), null));
    }
    
//        @Operation(summary = "根据用户ID获取用户任务统计信息", description = "包括总任务数、已完成任务数、剩余任务数以及任务列表")
        @GetMapping("/user/{userId}/statistics")
        public ResponseEntity<ApiResponse<UserTaskStatisticsDTO>> getUserTaskStatistics(
                        @PathVariable Long userId,
                        HttpServletRequest request) {
                UserTaskStatisticsDTO statistics = taskApprovalStatusService.getUserTaskStatistics(userId);
                return ResponseEntity.ok(
                                ApiResponse.success(statistics, "查询成功", request.getRequestURI(), null));
        }

//        @Operation(summary = "根据数据源ID获取该数据源下所有用户的审批统计信息", description = "包括每个用户的任务统计以及整体统计信息")
        @GetMapping("/datasource/{dataSourceId}/user-statistics")
        public ResponseEntity<ApiResponse<DataSourceUserStatisticsDTO>> getDataSourceUserStatistics(
                        @PathVariable Long dataSourceId,
                        HttpServletRequest request) {
            DataSourceUserStatisticsDTO statistics = taskApprovalStatusService.getDataSourceUserStatistics(dataSourceId);
            return ResponseEntity.ok(
                            ApiResponse.success(statistics, "查询成功", request.getRequestURI(), null));
        }

//        @Operation(summary = "根据数据源ID获取该数据源的任务统计信息", description = "包括总任务数、已完成、待处理、处理中、已拒绝、已跳过等状态的任务数")
        @GetMapping("/datasource/{dataSourceId}/task-statistics")
        public ResponseEntity<ApiResponse<DataSourceTaskStatisticsDTO>> getDataSourceTaskStatistics(
                        @PathVariable Long dataSourceId,
                        HttpServletRequest request) {
            DataSourceTaskStatisticsDTO statistics = taskApprovalStatusService.getDataSourceTaskStatistics(dataSourceId);
            return ResponseEntity.ok(
                            ApiResponse.success(statistics, "查询成功", request.getRequestURI(), null));
        }
}